var http = require("http");
var fs = require("fs");
var server = http.createServer((req, res) => {
  // 设置响应头
  res.writeHead(200, { 'Content-Type': 'text/html;charset=utf8' })
  res.end(fs.readFileSync('./聊天室.html'))
})



//socket	// nodejs-websocket 创建一个ws服务对象
const Server = require('ws').Server
var wss = new Server({ server })
var id = 0;
var clientMap = {

} //每个连接'
// websocket连接检测
wss.on('connection', function (socket) {//socket 客户端对象
  console.log(socket)
  id++;
  socket.id = id
  clientMap[socket.id] = socket; //把连接每个客户端对象存储到对象中
  console.log("有" + id + "人进入了聊天")

  // 客户端发送来的信息
  socket.on("message", function (msg) {
    console.log(msg)
    for (var id in clientMap) { //循环所有客户端  发送数据
      clientMap[id].send(msg);
    }
  })
  //当客户端断开的时候触发
  socket.on('close', function () {
    console.log("有人离开了聊天室")
  })
  //当客户端连接出错的时候
  socket.on('error', function (err) {
    console.log(err)
  })

})
server.listen(88, '169.254.184.38')